<link rel="stylesheet" href="style.css">
<template>
  <div class="form-approve-component-wrapper">
    <div class="form-approve-left">
      <div class="default-form-detail-header">
        <div class="flow-title">标题: {{ processInstance.processTitle }}</div>
        <div class="flow-info">发起人: {{ processInstance.applyByName }} <span
            style="margin-left: 10px">发起时间: {{ processInstance.createTime }}</span></div>
        <div style="margin-top: 10px">
          <el-button icon="view" @click="previewFlow" round>查看流程</el-button>
        </div>
      </div>

      <div class="default-form-detail-body">
        <div class="default-form-detail-content">
          <DefaultFormRender :pageAction="pageAction" :formDefinition="formDefinition" :viewAction="viewAction"
                             ref="DefaultFormRender" :view="view" :components="components"/>

          <FSection title="相关附件" v-show="isNotEmpty(formFlowDesc.attachmentIds)"
                    :style="{width: (view.width + 40) + 'px'}"
                    class="start-process-content-section">
            <FUploader ref="FUploader" :enable="false"/>
          </FSection>

          <FSection title="附言" :style="{width: (view.width + 40) + 'px'}"
                    class="start-process-content-section">
            <el-text>
              <div v-html="formFlowDesc.additionalComments">
              </div>
            </el-text>
          </FSection>

          <FSection title="处理人意见区" :style="{width: (view.width + 40) + 'px'}"
                    class="start-process-content-section">
            <FlowHistory :business-id="businessId"/>
          </FSection>
        </div>
      </div>
    </div>
    <div class="form-approve-right" v-show="pageAction !== 'static'">
      <ApproveComponent :formDefinition="formDefinition" :formFlowDesc="formFlowDesc" :userTask="userTask"
                        :getFormData="getFormData" ref="ApproveComponent"/>
    </div>
    <FlowPreviewModal ref="FlowPreviewModal"/>
    <FlowModelWithHistory ref="FlowModelWithHistory"/>
  </div>
</template>

<script>
import {getAction} from '@/request/BaseRequest';
import {DefaultViewAction, DefaultViewDefinition} from '@/components/form/DefaultFormDefinition';
import {getViewActionId, isEmpty, isNotEmpty} from '@/utils/CommonUtils';
import FlowPreviewModal from '@/components/flow/FlowPreviewModal';
import DefaultFormRender from '@/components/platwork/FormDetailComponent/DefaultFormDetailComponent/DefaultFormRender';
import FSection from '@/components/FSection';
import {DefaultFlowDefinition} from '@/components/flow/DefaultFlowDefinition';
import FUploader from '@/components/FUploader/index.vue';
import FModal from '@/components/FModal/index.vue';
import './style.css';
import {froalaConfig} from '@/components/MyFroala';
import FlowHistory from '@/components/platwork/FlowHistory/index.vue';
import FlowModelWithHistory from '@/components/platwork/FlowModelWithHistory';
import ApproveComponent from '@/components/platwork/FormApproveComponent/ApproveComponent';

export default {
  name: 'FormApproveComponent',
  components: {
    FUploader,
    FlowModelWithHistory,
    DefaultFormRender,
    FlowPreviewModal,
    FModal,
    FlowHistory,
    ApproveComponent,
    FSection
  },
  data() {
    return {
      components: [],
      view: DefaultViewDefinition,
      froalaConfig: {
        ...froalaConfig,
        zIndex: 2008,
      },
      config: {
        events: {
          initialized: function () {
            console.log('initialized');
          }
        }
      },
      viewAction: DefaultViewAction,
      formDefinition: {
        form: {},
        formFields: []
      },
      processInstance: {
        processTitle: undefined,
        applyBy: undefined,
        applyByName: undefined,
        createTime: undefined,
      },
      formFlowDesc: {
        attachmentIds: undefined,
        additionalComments: undefined,
        formDefinitionId: undefined,
        formName: undefined,
      },
      commentEditorFroala: false,
      userTask: {},
      businessId: this.$route.query.businessId,
      processDefinition: DefaultFlowDefinition,
      pageAction: 'edit' //edit, detail, approve, add, static
    };
  },
  mounted() {
    this.pageAction = this.$route.query.pageAction;

    if (this.pageAction === 'static') {
      this.loadProcessInstanceById();
      this.loadViewActionIdFormDefinitionPublishedByViewActionId().then(() => {
        this.loadAndSetFormData();
      });
    } else {
      this.loadProcessDataByUserTaskId(() => {
        this.loadViewActionIdFormDefinitionPublished().then(() => {
          this.loadAndSetFormData();
        });
      });
    }
  },
  methods: {
    isNotEmpty,
    loadProcessDataByUserTaskId(callback) {
      let userTaskId = this.$route.query.userTaskId;
      this.loading = true;
      getAction('/flow/loadProcessDataByUserTaskId', {userTaskId}).then(data => {
        this.loading = false;
        if (data.success) {
          let result = data.result;
          if (isEmpty(result)) return;
          this.setProcessDefinition(result);
          callback();
        }
      });
    },
    previewFlow() {
      // this.$refs.FlowPreviewModal.setData({id: this.processDefinition.id});
      this.$refs.FlowModelWithHistory.setData(this.processInstance.id);
      if (isNotEmpty(this.userTask.taskName)) {
        this.$refs.FlowModelWithHistory.setHeader(`当前节点: ${this.userTask.taskName}`);
      } else {
        this.$refs.FlowModelWithHistory.setHeader(`查看流程`);
      }
    },
    setProcessDefinition(result) {
      this.userTask = result.userTask;
      this.processDefinition = result.processDefinition;
      this.processInstance = result.processInstance;
      this.resolvePageAction();
    },
    resolvePageAction() {
      if (this.userTask.active === false) {
        this.pageAction = 'static';
      }
    },
    getFormData() {
      return this.$refs.DefaultFormRender.getFormDataWithCheck();
    },
    loadProcessInstanceById() {
      let processInstanceId = this.$route.query.processInstanceId;
      this.loading = true;
      getAction('/flow/loadProcessInstanceById', {processInstanceId}).then(data => {
        this.loading = false;
        if (data.success) {
          let result = data.result;
          this.processInstance = result;
        }
      });
    },
    loadViewActionIdFormDefinitionPublishedByViewActionId() {
      return new Promise((success, err) => {
        let viewActionId = this.$route.query.viewActionId;
        if (isEmpty(viewActionId)) return;

        getAction('/plat/loadviewActionIdFormDefinitionPublished', {viewActionId}).then(data => {
          this.loading = false;
          if (data.success) {
            let result = data.result;
            this.setViewActionIdFormDefinitionPublished(result);
            success();
          }
        });
      });
    },
    loadViewActionIdFormDefinitionPublished() {
      return new Promise((success, err) => {
        let viewActionId = getViewActionId(this.userTask);
        this.loading = true;
        getAction('/plat/loadviewActionIdFormDefinitionPublished', {viewActionId}).then(data => {
          this.loading = false;
          if (data.success) {
            let result = data.result;
            this.setViewActionIdFormDefinitionPublished(result);
            success();
          }
        });
      });
    },
    setViewActionIdFormDefinitionPublished(result) {
      this.setViewDefinition(result.views[0]);
      this.setViewAction(result.viewAction);
      this.setFormDefinition1(result);
    },
    setViewDefinition(data) {
      data.viewDefinition = JSON.parse(data.viewDefinition);
      this.view = data;
      this.components = this.view.viewDefinition.children;
    },
    setViewAction(viewAction) {
      this.viewAction = viewAction;
    },
    loadAndSetFormData() {
      this.$refs.DefaultFormRender.setFormDefinition(this.formDefinition);
      let formId = this.formDefinition.form.id;
      let id = this.$route.query.businessId;
      this.loading = true;
      getAction('/plat/loadFormDataById', {id, formId}).then(data => {
        this.loading = false;
        if (data.success) {
          let result = data.result;
          this.setFormData(result);
        }
      });
    },
    setFormData(result) {
      this.formData = result.formData;
      this.formFlowDesc = result.formFlowDesc;
      this.$refs.DefaultFormRender.setFormData(this.formData);
      this.$refs.FUploader.setData(this.formFlowDesc.attachmentIds);
    },
    setFormDefinition1(formDefinition) {
      if (isEmpty(formDefinition)) return;
      this.formDefinition.form = formDefinition;
      this.formDefinition.formFields = formDefinition.fields;
      this.formDefinition.formRelationVos = formDefinition.formRelationVos;

      let tempSubForms = [];
      if (isNotEmpty(formDefinition.subForms)) {
        formDefinition.subForms.forEach(subForm => {
          tempSubForms.push({
            fields: subForm.fields,
            subForm
          });
        });
      }
      this.formDefinition.subForms = tempSubForms;
      this.$refs.DefaultFormRender.setFormDefinition(this.formDefinition);
    },
  }
};
</script>
